package com.liholin.springboot.sample.controller;

import com.liholin.springboot.sample.configdata.ResponseData;
import com.liholin.springboot.sample.exception.ErrorStatus;
import com.liholin.springboot.sample.service.UploadFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class UploadFileController {
    @Autowired
    private UploadFileService uploadFileService;

    /**
     * 批量上传图片和视频，也可以增加json数据
     *
     * @param files
     * @return
     */
    @PostMapping(value = "/multipleImageUpload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseData multipleImageUpload(@RequestParam("file") MultipartFile[] files) throws IOException {
        log.info("上传的图片数：" + files.length);

        List<MultipartFile> multipartFiles = new ArrayList();

        for (MultipartFile file : files) {    //循环保存文件
            if (file.getSize() / 1000 > 50 * 1024) {
                //图片大小不能超过20m
                return ResponseData.Companion.error(ErrorStatus.FILE_SIZE_ERROR);
            } else {
                //判断上传文件格式
                String fileType = file.getContentType();
                if (fileType.equals("image/jpeg") || fileType.equals("image/png") || fileType.equals("image/jpg") || fileType.equals("video/avi") || fileType.equals("video/mov") || fileType.equals("video/mp4")) {
                    // 要上传的目标文件存放的绝对路径
                    final String localPath = "/tmp/upload";
                    //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
                    //获取文件名
                    String fileName = file.getOriginalFilename();
                    //获取文件后缀名
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));

                    multipartFiles.add(file);

                } else {
                    // 图片格式不正确
                    return ResponseData.Companion.error(ErrorStatus.FILE_FORMAT_ERROR);
                }
            }
        }
        try {
            if (multipartFiles.size() > 0) {
                List urlList = new ArrayList();
                urlList = uploadFileService.multipleImageUpload(multipartFiles);
                return ResponseData.Companion.ok(urlList);
            } else {
                return ResponseData.Companion.ok(multipartFiles);
            }

        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }
}
